package org.belkodevelop.controller.interceptor;

import org.belkodevelop.announcement.service.AnnouncementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ConstantsInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private AnnouncementService announcementService;

    private Map<String, Object> cache;

    private Date dateCreate;

    private static final int SECOND_RECREATE_CACHE = 1;

    private static final String MAX_PRICE_REALTY_FOR_RENT = "MAX_PRICE_REALTY_FOR_RENT";
    private static final String MAX_PRICE_REALTY_FOR_SALE = "MAX_PRICE_REALTY_FOR_SALE";

    @PostConstruct
    public void createCache() {
        dateCreate = new Date();
        cache = new HashMap<>();

        float maxPriceForRent = announcementService.getMaxPriceForRent() == null ?
                0 : announcementService.getMaxPriceForRent();
        float maxPriceForSale = announcementService.getMaxPriceForSale() == null ?
                0 : announcementService.getMaxPriceForSale();

        cache.put(MAX_PRICE_REALTY_FOR_RENT, maxPriceForRent);
        cache.put(MAX_PRICE_REALTY_FOR_SALE, maxPriceForSale);
    }

    private void addConstantsToModelAndView(ModelAndView modelAndView) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND, SECOND_RECREATE_CACHE);
        if (dateCreate.before(calendar.getTime())) {
            createCache();
        }
        for (String key: cache.keySet()) {
            modelAndView.addObject(key, cache.get(key));
        }
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

        if (modelAndView != null) {
            addConstantsToModelAndView(modelAndView);
        }
        super.postHandle(request, response, handler, modelAndView);
    }
}
